// behaviors/myBehavior.js
import Http from '@/services/api/index';
const Storage = require('./../utils/storage.js')
const Toast = require('./../utils/toast.js')
const Config = require('./../config/base_config.js')

module.exports = Behavior({
  // 定义数据
  data: {
    sharedData: '这是共享数据',
    ASSETS_URL: Config.ASSETS_URL,
  },

  // 定义方法
  methods: {
    clearAllStorage() {
      wx.clearStorage()
    },
    sharedMethod() {
      console.log('这是共享方法');
      Storage.get("access_token")
      Storage.get("refresh_token")
      Storage.get("userInfo")
      this.setData({
        sharedData: '数据已更新'
      });
    },
    async addToCart(e) {
      const {
        id
      } = e.currentTarget.dataset;
      try {
        await Http.post('/api/cart/add', {
          productId: id,
          quantity: 1
        }, {
          skipAuth: false
        }).then((res) => {
          Toast.success(res.message);
        }).catch(err => {
          console.error(err)
        })
      } catch (err) {
        console.error('添加购物车失败', err);
      }
    },
    navigateToPage(e) {
      console.log(e)
      const {
        url,
        type
      } = e.currentTarget.dataset;
      console.log(type, url)
      // --后续控制逻辑
      if (type == "redirect") {
        wx.redirectTo({
          url
        })
        return;
      }
      // --后续控制逻辑
      wx.navigateTo({
        url
      })
    },
    goToDetailPage(e) {
      const {
        id
      } = e.currentTarget.dataset;
      // --后续控制逻辑
      wx.navigateTo({
        url: `/sub-packages/product/pages/detail/index?id=${id}`
      })
    },

    redirectToLogin() {
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const currentRoute = currentPage.route;
      const currentOptions = currentPage.options || {};
      console.log(`/pages/login/index?redirect=${encodeURIComponent(currentRoute)}&params=${encodeURIComponent(JSON.stringify(currentOptions))}`)
      wx.redirectTo({
        url: `/pages/login/index?redirect=${encodeURIComponent(currentRoute)}&params=${encodeURIComponent(JSON.stringify(currentOptions))}`
      });
    }
  },
});